import 'dart:io';

import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:get/get.dart';
import 'package:kq_flutter_core_widget/widgets/image/kq_image.dart';
import 'package:kq_flutter_core_widget/widgets/imageBox/kq_image_box.dart';
import 'package:kq_flutter_core_widget/widgets/image/oss_image_provider.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';

import '../../../config/kq_global.dart';
import '../../../resources/images.dart';
import '../../../widgets/indicator/kq_page_indicator.dart';
import '../../../widgets/titleBar/kq_title_bar.dart';

/// 图片预览界面
class ImgPreviewPage extends StatefulWidget {
  const ImgPreviewPage({super.key});

  @override
  ImgPreviewPageState createState() => ImgPreviewPageState();
}

class ImgPreviewPageState extends State<ImgPreviewPage> {
  late List<ImageUrl> imageUrls;
  int position = 0;
  PageController? pageController;

  @override
  void initState() {
    super.initState();
    imageUrls = Get.arguments;
    var params = Get.parameters;
    position = int.parse(params['position'] ?? '0');
    pageController = PageController(initialPage: position);
  }

  ImageProvider _buildProvider(ImageUrl imageUrl) {
    switch (imageUrl.imageType) {
      case ImageType.file:
        return FileImage(File(imageUrl.url));
      case ImageType.http:
        return NetworkImage(imageUrl.url);
      case ImageType.oss:
        if (imageUrl.url.startsWith("http")) {
          return NetworkImage(imageUrl.url);
        }
        return OSSImageProvider(imageUrl.url);
      case ImageType.assets:
        return AssetImage(imageUrl.url);
      case ImageType.memory:
        return MemoryImage(imageUrl.extra);
    }
  }

  @override
  void didUpdateWidget(covariant ImgPreviewPage oldWidget) {
    super.didUpdateWidget(oldWidget);
    imageUrls = Get.arguments;
    var params = Get.parameters;
    position = int.parse(params['position'] ?? '0');
    pageController = PageController(initialPage: position);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: KqHeadBar(
        showBack: true,
        bgColor: Colors.black,
        back: () {
          Get.back();
        },
        headTitle: '${position + 1}/${imageUrls.length}',
      ),
      body: Stack(
        children: [
          PhotoViewGallery.builder(
            scrollPhysics: const BouncingScrollPhysics(),
            builder: (BuildContext context, int index) {
              var imageUrl = imageUrls[index];
              return PhotoViewGalleryPageOptions(
                imageProvider: _buildProvider(imageUrl),
                initialScale: PhotoViewComputedScale.contained * 1.0,
                heroAttributes: PhotoViewHeroAttributes(
                  tag: imageUrl.url,
                ),
                errorBuilder: (context, error, stackTrace) {
                  return Image.asset(Images.commonPicQuesheng1024,
                      package: KqGlobal.packageName, fit: BoxFit.contain);
                },
              );
            },
            pageController: pageController,
            itemCount: imageUrls.length,
            onPageChanged: (index) {
              setState(() {
                position = index;
              });
            },
            loadingBuilder: (context, event) => Center(
              child: event == null || event.expectedTotalBytes == null
                  ? SizedBox(
                      width: 50.r,
                      height: 50.r,
                      child: const CircularProgressIndicator(),
                    )
                  : SizedBox(
                      width: 20.r,
                      height: 20.r,
                      child: CircularProgressIndicator(
                        value: event.cumulativeBytesLoaded /
                            event.expectedTotalBytes!,
                      ),
                    ),
            ),
          ),
          Positioned(
              left: 0,
              right: 0,
              bottom: 64.r + KqScreenUtil().bottomBarHeight,
              child: KqPageIndicator(
                index: position,
                count: imageUrls.length,
              ))
        ],
      ),
    );
  }
}
